﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdateService.Mgr.Handler
{
    using AutoUpdate.Model.Packet;
    public class downloadFileHandler : Handler
    {
        public downloadFileHandler()
        {
            this.name = "downloadFile";
        }

        public override void doAction(Packet packet)
        {
            string versionPath = Environment.CurrentDirectory + "\\" + ConfigMgr.getInstance().config.versionPath;

            AutoUpdate.Model.Model.fileTransfer.fs_inodeContent inodeModel = AutoUpdate.Utility.Helper.JsonHelper.getObject<AutoUpdate.Model.Model.fileTransfer.fs_inodeContent>(packet.MessageContent);

            if (inodeModel != null)
            {
                int fileBlockLength = 32 * 1024;

                string fileName = versionPath + "\\" + "ver" + inodeModel.version + "\\" + inodeModel.md5;

                int length = 0;

                inodeModel.contents = AutoUpdate.Utility.Helper.FileHelper.fileRead(fileName, inodeModel.offset, fileBlockLength, out length);

                if (length > 0)
                {
                    inodeModel.length = length;
                }

                AutoUpdate.Model.Packet.ResponsePacket response = new ResponsePacket();

                packet.FillData(response);

                response.PacketType = PacketType.Response;

                response.MessageContent = Newtonsoft.Json.JsonConvert.SerializeObject(inodeModel);

                ClientMgr.getInstance().transferMessage(response);
            }
        }
    }
}
